package com.sso.server.controller;

import com.sso.core.conf.SSOConf;
import com.sso.server.core.model.UserInfo;
import com.sso.server.core.result.ReturnData;
import com.sso.server.service.UserService;
import com.sso.core.login.SsoTokenLoginHelper;
import com.sso.core.store.SsoLoginStore;
import com.sso.core.user.SsoUser;
import com.sso.core.store.SsoSessionIdHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.UUID;

/**
 * sso server (for app)
 *
 */
@Controller
@RequestMapping("/app")
public class AppController {

    @Autowired
    private UserService userService;



    /**
     * Login
     *
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(SSOConf.SSO_LOGIN)
    @ResponseBody
    public ReturnData<String> login(String username, String password) {

        ReturnData<UserInfo> result = userService.findUser(username, password);
        if (result.getCode() != ReturnData.SUCCESS_CODE) {
            return new ReturnData<String>(result.getCode(), result.getMsg());
        }

        SsoUser ssoUser= new SsoUser();
        ssoUser.setUsername(result.getData().getUsername());
        ssoUser.setId(result.getData().getId());
        ssoUser.setVersion(UUID.randomUUID().toString().replaceAll("-", ""));
        ssoUser.setExpireMinute(SsoLoginStore.getRedisExpireMinute());
        ssoUser.setExpireFreshTime(System.currentTimeMillis());


        String sessionId = SsoSessionIdHelper.makeSessionId(ssoUser);

        SsoTokenLoginHelper.login(sessionId, ssoUser);

        return new ReturnData<String>(sessionId);
    }


    /**
     * Logout
     *
     * @param ticket
     * @return
     */
    @RequestMapping(SSOConf.SSO_LOGOUT)
    @ResponseBody
    public ReturnData<String> logout(String ticket) {
        // logout, remove storeKey
        SsoTokenLoginHelper.logout(ticket);
        return ReturnData.SUCCESS;
    }

    /**
     * check
     *
     * @param ticket
     * @return
     */
    @RequestMapping(SSOConf.SSO_CHECK)
    @ResponseBody
    public ReturnData<SsoUser> check(String ticket) {

        SsoUser ssoUser = SsoTokenLoginHelper.loginCheck(ticket);
        if (ssoUser == null) {
            return new ReturnData<SsoUser>(ReturnData.FAIL_CODE, "sso not login.");
        }
        return new ReturnData<SsoUser>(ssoUser);
    }

    /**
     * 当用户账号表发生变化时请调用此
     * 刷新账号缓存资料
     * @param ticket
     * @return
     */
    @RequestMapping("referAccountInfo")
    @ResponseBody
    public ReturnData<String> referAccountInfo(String ticket) {

        userService.initUserInfo();
        return ReturnData.SUCCESS;
    }

}
